/**
 * 通知中心页面逻辑
 */

const { ipcRenderer } = require('electron');
const log = require('electron-log');
const {
  showNotification,
  setupWindowControls,
  navigateToPage,
  getUserData,
  formatDate
} = require('../utils/common');

// 通知数据存储
let notifications = [];
let currentFilter = 'all';

// 页面初始化
window.addEventListener('DOMContentLoaded', () => {
  // 检查登录状态
  const userData = getUserData();
  if (!userData) {
    navigateToPage('login');
    return;
  }

  // 设置窗口控制
  setupWindowControls();

  // 绑定事件
  bindEvents();

  // 加载通知
  loadNotifications();

  // 监听通知更新事件
  ipcRenderer.on('notification-updated', () => {
    log.info('收到通知更新事件，重新加载通知列表');
    loadNotifications();
  });

  log.info('通知中心页面初始化完成');
});

// 绑定事件
function bindEvents() {
  // 按钮事件
  document.getElementById('back-btn')?.addEventListener('click', () => {
    navigateToPage('main');
  });

  document.getElementById('mark-all-read-btn')?.addEventListener('click', markAllAsRead);
  document.getElementById('clear-all-btn')?.addEventListener('click', clearAllNotifications);

  // 筛选按钮
  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      currentFilter = btn.dataset.filter;
      
      // 更新按钮状态
      document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      
      // 重新渲染列表
      renderNotifications();
    });
  });
}

// 加载通知
function loadNotifications() {
  const saved = localStorage.getItem('appNotifications');
  if (saved) {
    try {
      notifications = JSON.parse(saved);
    } catch (error) {
      log.error('加载通知失败:', error);
      notifications = [];
    }
  }

  // 如果没有通知，添加一些示例通知
  if (notifications.length === 0) {
    notifications = getSampleNotifications();
    saveNotifications();
  }

  renderNotifications();
}

// 渲染通知列表
function renderNotifications() {
  const container = document.getElementById('notifications-list');
  if (!container) return;

  // 筛选通知
  let filtered = notifications;
  if (currentFilter !== 'all') {
    filtered = notifications.filter(n => n.type === currentFilter);
  }

  // 如果没有通知
  if (filtered.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <div class="empty-state-text">暂无通知</div>
      </div>
    `;
    return;
  }

  // 渲染通知项
  container.innerHTML = '';
  filtered.forEach(notification => {
    const item = createNotificationItem(notification);
    container.appendChild(item);
  });
}

// 创建通知项
function createNotificationItem(notification) {
  const item = document.createElement('div');
  item.className = `notification-item ${notification.type}`;
  if (!notification.read) {
    item.classList.add('unread');
  }

  item.innerHTML = `
    <div class="notification-content">
      <div class="notification-title">${notification.title}</div>
      <div class="notification-message">${notification.message}</div>
      <div class="notification-meta">
        <span>${formatDate(notification.timestamp)}</span>
        ${!notification.read ? '<span style="color: #2f80ff;">● 未读</span>' : ''}
      </div>
    </div>
    <div class="notification-actions">
      <button class="notification-btn" data-action="detail" data-id="${notification.id}">查看详情</button>
      ${!notification.read ? `<button class="notification-btn" data-action="read" data-id="${notification.id}">标记已读</button>` : ''}
      <button class="notification-btn" data-action="delete" data-id="${notification.id}">删除</button>
    </div>
  `;

  // 绑定按钮事件
  item.querySelectorAll('.notification-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const action = btn.dataset.action;
      const id = btn.dataset.id;
      
      if (action === 'detail') {
        openNotificationDetail(id);
      } else if (action === 'read') {
        markAsRead(id);
      } else if (action === 'delete') {
        deleteNotification(id);
      }
    });
  });

  return item;
}

// 打开通知详情窗口
function openNotificationDetail(id) {
  // 向主进程发送打开通知详情窗口的请求
  ipcRenderer.send('open-notification-detail', id);
  log.info('打开通知详情:', id);
}

// 标记为已读
function markAsRead(id) {
  const notification = notifications.find(n => n.id === id);
  if (notification) {
    notification.read = true;
    saveNotifications();
    renderNotifications();
  }
}

// 全部标记为已读
function markAllAsRead() {
  notifications.forEach(n => n.read = true);
  saveNotifications();
  renderNotifications();
  showNotification('已全部标记为已读', 'info');
}

// 删除通知
function deleteNotification(id) {
  notifications = notifications.filter(n => n.id !== id);
  saveNotifications();
  renderNotifications();
  showNotification('通知已删除', 'info');
}

// 清空所有通知
function clearAllNotifications() {
  if (confirm('确定要清空所有通知吗？')) {
    notifications = [];
    saveNotifications();
    renderNotifications();
    showNotification('已清空所有通知', 'info');
  }
}

// 保存通知
function saveNotifications() {
  localStorage.setItem('appNotifications', JSON.stringify(notifications));
}

// 添加新通知（供其他模块调用）
function addNotification(title, message, type = 'info') {
  const notification = {
    id: Date.now().toString(),
    title,
    message,
    type,
    timestamp: new Date().toISOString(),
    read: false
  };
  
  notifications.unshift(notification);
  
  // 最多保留100条通知
  if (notifications.length > 100) {
    notifications = notifications.slice(0, 100);
  }
  
  saveNotifications();
}

// 获取示例通知
function getSampleNotifications() {
  const now = new Date();
  return [
    {
      id: '1',
      title: '欢迎使用 FTP Rush',
      message: '感谢您使用 FTP Rush 文件传输工具！',
      type: 'success',
      timestamp: new Date(now.getTime() - 1000 * 60).toISOString(),
      read: false
    },
    {
      id: '2',
      title: '文件上传成功',
      message: '文件 "report.pdf" 已成功上传到服务器',
      type: 'success',
      timestamp: new Date(now.getTime() - 1000 * 60 * 5).toISOString(),
      read: false
    },
    {
      id: '3',
      title: 'FTP连接警告',
      message: 'FTP服务器连接不稳定，建议检查网络',
      type: 'warning',
      timestamp: new Date(now.getTime() - 1000 * 60 * 30).toISOString(),
      read: true
    },
    {
      id: '4',
      title: '系统提示',
      message: '发现新版本 v1.1.0，建议更新',
      type: 'info',
      timestamp: new Date(now.getTime() - 1000 * 60 * 60).toISOString(),
      read: true
    }
  ];
}

// 导出函数供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { addNotification };
}
